package bTree.LeetCode;

import java.util.ArrayList;
import java.util.List;

public class 路径总和2 {
    List<List<Integer>> res = new ArrayList<>();

    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        if(root==null){
            return res;
        }
        List<Integer> path = new ArrayList<>();
        int sum = 0;
        dfs(root, targetSum, path, sum);
        return res;
    }

    private void dfs(TreeNode root, int targetSum, List<Integer> path, int sum) {
        if (root.left == null && root.right == null) {
            sum += root.val;
            path.add(root.val);
            if (sum == targetSum) {
                res.add(new ArrayList<>(path));
            }
            return;
        }
        sum += root.val;
        path.add(root.val);
        if (root.left != null) {
            dfs(root.left, targetSum, path, sum);
            path.remove(path.size()-1);
        }
        if (root.right != null) {
            dfs(root.right, targetSum, path, sum);
            path.remove(path.size()-1);
        }
    }
}